package org.jeecg.modules.extbpm.process.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ActivitiException;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.bpm.util.BpmUtil;
import org.jeecg.modules.extbpm.process.common.WorkFlowGlobals;
import org.jeecg.modules.extbpm.process.entity.ExtActDesignFlowData;
import org.jeecg.modules.extbpm.process.entity.ExtActFlowData;
import org.jeecg.modules.extbpm.process.entity.ExtActProcessForm;
import org.jeecg.modules.extbpm.process.exception.BpmException;
import org.jeecg.modules.extbpm.process.pojo.DesFormFlowDTO;
import org.jeecg.modules.extbpm.process.pojo.DesignFormDataDTO;
import org.jeecg.modules.extbpm.process.service.IExtActDesignFlowDataService;
import org.jeecg.modules.extbpm.process.service.IExtActProcessFormService;
import org.jeecg.modules.extbpm.process.service.IExtActProcessService;
import org.jeecg.modules.extbpm.util.JSONHelper;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 表单设计器对接流程
 * @Author: jeecg-boot
 * @Date: 2019-06-26
 * @Version: V1.0
 */
@Slf4j
@Api(tags="自定义表单流程对接")
@RestController("extActDesignFlowData")
@RequestMapping("/act/process/extActDesignFlowData")
public class ExtActDesignFlowDataController {

	@Autowired
	private IExtActDesignFlowDataService extActDesignFlowDataService;
	@Autowired
	private IExtActProcessService extActProcessService;
	@Autowired
	private IExtActProcessFormService extActProcessFormService;

	/**
	 * 分页列表查询
	 * 
	 * @param extActDesignFlowData
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<ExtActDesignFlowData>> queryPageList(ExtActDesignFlowData extActDesignFlowData, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		Result<IPage<ExtActDesignFlowData>> result = new Result<IPage<ExtActDesignFlowData>>();
		if(oConvertUtils.isNotEmpty(extActDesignFlowData.getProcessName())) {
			extActDesignFlowData.setProcessName("*"+extActDesignFlowData.getProcessName()+"*");
		}
		QueryWrapper<ExtActDesignFlowData> queryWrapper = QueryGenerator.initQueryWrapper(extActDesignFlowData, req.getParameterMap());
		String username = JwtUtil.getUserNameByToken(req);
		queryWrapper.lambda().eq(ExtActDesignFlowData::getCreateBy, username);
		Page<ExtActDesignFlowData> page = new Page<ExtActDesignFlowData>(pageNo, pageSize);
		IPage<ExtActDesignFlowData> pageList = extActDesignFlowDataService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	 * 查询关联流程的设计器表单
	 * 
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/getDesFormFlows")
	public Result<List<DesFormFlowDTO>> getDesFormFlows(HttpServletRequest req) {
		Result<List<DesFormFlowDTO>> result = new Result<List<DesFormFlowDTO>>();
		List<DesFormFlowDTO> list = extActDesignFlowDataService.getDesFormFlows();
		result.setResult(list);
		return result;
	}
	
	/**
	 * 根据流程类型查询关联流程的自定义表单
	 * @TODO 作废接口
	 * 
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/getDesFormFlowsByProcType")
	@Deprecated
	public Result<List<DesFormFlowDTO>> getDesFormFlowsByProcType(@RequestParam(name = "procType") String procType,HttpServletRequest req) {
		Result<List<DesFormFlowDTO>> result = new Result<List<DesFormFlowDTO>>();
		List<DesFormFlowDTO> list = extActDesignFlowDataService.getDesFormFlowsByProcType(procType);
		result.setSuccess(true);
		result.setResult(list);
		return result;
	}

	/**
	 * 添加
	 * 
	 * @param extActDesignFlowData
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ExtActDesignFlowData extActDesignFlowData,HttpServletRequest request) {
		Result<String> result = new Result<>();
		try {
			//获取表名，根据数据计算业务标题
			DesignFormDataDTO designFormDataDTO = extActDesignFlowDataService.getDesignFormDataById(extActDesignFlowData.getDesformDataId());
			extActDesignFlowData.setTableName(designFormDataDTO.getOnlineFormCode());
			Map<String, Object> dataForm = new HashMap<String, Object>();
			dataForm = JSONHelper.json2MapNoObj(designFormDataDTO.getDesformDataJson());
			String bizTitle =  BpmUtil.getContent(dataForm,extActDesignFlowData.getTitleExp());
			extActDesignFlowData.setBpmTitle(bizTitle);
			extActDesignFlowData.setBpmStatus(WorkFlowGlobals.BPM_BUS_STATUS_1);
			extActDesignFlowDataService.save(extActDesignFlowData);
			result.setResult(extActDesignFlowData.getId());
			//update-begin--- author:scott---date:20200313------for:移动OA统一草稿箱功能（online表单+设计器表单）,在保存表单时，判断关联流程的话则往流程中间表插入表单数据------------
			try {
				// 执行流程草稿保存
				// TODO
				//获取当前发起人
				String username = JwtUtil.getUserNameByToken(request);
				//查询流程业务关联配置
				LambdaQueryWrapper<ExtActProcessForm> queryWrapper = new LambdaQueryWrapper<ExtActProcessForm>();
				queryWrapper.eq(ExtActProcessForm::getRelationCode, extActDesignFlowData.getFlowCode());
				ExtActProcessForm extActProcessForm = extActProcessFormService.getOne(queryWrapper);
				//获取业务数据，并且加载到流程变量中
				String tableName = extActProcessForm.getFormTableName();
				ExtActFlowData extActFlowData = extActProcessService.saveMutilProcessDraft(username, extActDesignFlowData.getId(), extActProcessForm);
			} catch (Exception e) {
				e.printStackTrace();
			}
			//update-end--- author:scott---date:20200313------for:移动OA统一草稿箱功能（online表单+设计器表单）,在保存表单时，判断关联流程的话则往流程中间表插入表单数据------------
			result.success("添加成功！");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}


	/**
	 * 保存单据并提交流程接口（表单设计器单据）
	 *
	 * @param request
	 * @return
	 */
	@PostMapping(value = "saveAndStartDesFormMutilProcess")
	public Result<String> saveAndStartDesFormMutilProcess(@RequestBody ExtActDesignFlowData extActDesignFlowData, HttpServletRequest request) {
		Result<String> result = new Result<String>();
		try {
			String id = extActDesignFlowDataService.saveAndStartDesFormMutilProcess(extActDesignFlowData, request);
			result.setResult(id);
			result.setMessage("流程发起成功！");
		} catch (ActivitiException e) {
			String message = "启动流程失败";
			if (e.getMessage().indexOf("no processes deployed with key") != -1) {
				message = "没有部署流程!,请在流程配置中部署流程!";
			} else if (e.getMessage().indexOf("Error while evaluating expression") != -1) {
				message = "启动流程失败,流程表达式异常!";
				try {
					message += e.getCause().getCause().getMessage();
				} catch (Exception e1) {
				}
			} else {
				message = "启动流程失败!请确认流程和表单是否关联!";
			}
			result.error500(message);
			Object actObj = e.getCause();
			if (actObj != null) {
				Throwable throwable = (Throwable) actObj;
				if (throwable.getCause() != null && throwable.getCause() instanceof BpmException) {
					result.error500("启动流程失败:" + throwable.getCause().getMessage());
				}
			}
			e.printStackTrace();
		} catch (BpmException e) {
			result.error500("启动流程失败:" + e.getMessage());
			e.printStackTrace();
		} catch (Exception e) {
			result.error500("启动流程失败!,请确认流程和表单是否关联!");
			e.printStackTrace();
			Object actObj = e.getCause();
			if (actObj != null) {
				Throwable throwable = (Throwable) actObj;
				if (throwable.getCause() != null && throwable.getCause() instanceof BpmException) {
					result.error500("启动流程失败:" + throwable.getCause().getMessage());
				}
			}
		}
		return result;
	}


	/**
	 * 编辑
	 * 
	 * @param extActDesignFlowData
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<ExtActDesignFlowData> edit(@RequestBody ExtActDesignFlowData extActDesignFlowData) {
		Result<ExtActDesignFlowData> result = new Result<ExtActDesignFlowData>();
		LambdaQueryWrapper<ExtActDesignFlowData> queryWrapper = new LambdaQueryWrapper<ExtActDesignFlowData>();
		queryWrapper.eq(ExtActDesignFlowData::getDesformDataId, extActDesignFlowData.getDesformDataId());
		ExtActDesignFlowData extActDesignFlowDataEntity = extActDesignFlowDataService.getOne(queryWrapper);
//		ExtActDesignFlowData extActDesignFlowDataEntity = extActDesignFlowDataService.getById(extActDesignFlowData.getId());
		if (extActDesignFlowDataEntity == null) {
			result.error500("未找到对应实体");
		} else {
			//获取表名，根据数据计算业务标题
			DesignFormDataDTO designFormDataDTO = extActDesignFlowDataService.getDesignFormDataById(extActDesignFlowData.getDesformDataId());
			Map<String, Object> dataForm = new HashMap<String, Object>();
			dataForm = JSONHelper.json2MapNoObj(designFormDataDTO.getDesformDataJson());
			String bizTitle =  BpmUtil.getContent(dataForm,extActDesignFlowDataEntity.getTitleExp());
			extActDesignFlowDataEntity.setBpmTitle(bizTitle);
			boolean ok = extActDesignFlowDataService.updateById(extActDesignFlowDataEntity);
			if (ok) {
				result.success("修改成功!");
			}
		}

		return result;
	}

	/**
	 * 通过id删除
	 * 
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
		try {
			extActDesignFlowDataService.removeById(id);
		} catch (Exception e) {
			log.error("删除失败", e.getMessage());
			return Result.error("删除失败!");
		}
		return Result.ok("删除成功!");
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<ExtActDesignFlowData> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		Result<ExtActDesignFlowData> result = new Result<ExtActDesignFlowData>();
		if (ids == null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		} else {
			this.extActDesignFlowDataService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}

	/**
	 * 通过id查询
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<ExtActDesignFlowData> queryById(@RequestParam(name = "id", required = true) String id) {
		Result<ExtActDesignFlowData> result = new Result<ExtActDesignFlowData>();
		ExtActDesignFlowData extActDesignFlowData = extActDesignFlowDataService.getById(id);
		if (extActDesignFlowData == null) {
			result.error500("未找到对应实体");
		} else {
			result.setResult(extActDesignFlowData);
			result.setSuccess(true);
		}
		return result;
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
		// Step.1 组装查询条件
		QueryWrapper<ExtActDesignFlowData> queryWrapper = null;
		try {
			String paramsStr = request.getParameter("paramsStr");
			if (oConvertUtils.isNotEmpty(paramsStr)) {
				String deString = URLDecoder.decode(paramsStr, "UTF-8");
				ExtActDesignFlowData extActDesignFlowData = JSON.parseObject(deString, ExtActDesignFlowData.class);
				queryWrapper = QueryGenerator.initQueryWrapper(extActDesignFlowData, request.getParameterMap());
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// Step.2 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		List<ExtActDesignFlowData> pageList = extActDesignFlowDataService.list(queryWrapper);
		// 导出文件名称
		mv.addObject(NormalExcelConstants.FILE_NAME, "表单设计器对接流程列表");
		mv.addObject(NormalExcelConstants.CLASS, ExtActDesignFlowData.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("表单设计器对接流程列表数据", "导出人:Jeecg", "导出信息"));
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ExtActDesignFlowData> listExtActDesignFlowDatas = ExcelImportUtil.importExcel(file.getInputStream(), ExtActDesignFlowData.class, params);
				extActDesignFlowDataService.saveBatch(listExtActDesignFlowDatas);
				return Result.ok("文件导入成功！数据行数:" + listExtActDesignFlowDatas.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.ok("文件导入失败！");
	}

}
